<template>
  <div class="app-container">
    <el-form :model="form" :rules="rules" ref="form" label-width="120px">
      <!-- 序号输入框 -->
      <el-form-item label="序号" prop="urlId">
        <el-input v-model="form.urlId" placeholder="请输入序号"></el-input>
      </el-form-item>

      <!-- 直播名称输入框 -->
      <el-form-item label="直播名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入直播名称"></el-input>
      </el-form-item>

      <!-- 直播图标 -->
      <el-form-item label="直播图标" prop="image">
        <div style="display: flex; align-items: center;">
          <!-- 上传图标 -->
          <el-upload
            :action="uploadUrl"
            :headers="headers"
            :on-success="handleIconUploadSuccess"
            :on-error="handleIconUploadError"
            list-type="picture-card"
            :show-file-list="false">
            <!-- 图片回显 -->
            <img v-if="form.image" :src="form.image" alt="直播图标" style="margin-left: auto; max-width: 160px; max-height: 160px;">
          </el-upload>
          <!-- 或者填写URL -->
          <el-form-item style="margin-left: 20px; flex-grow: 1;" label="或" prop="imageUrl">
            <el-input v-model="form.image" placeholder="请输入图标URL"></el-input>
          </el-form-item>
        </div>
      </el-form-item>

      <!-- 高画质流输入框 -->
      <el-form-item label="高画质流" prop="highQualityStream">
        <el-input v-model="form.highQualityStream" placeholder="请输入高画质流地址"></el-input>
      </el-form-item>

      <!-- 高画质流密码输入框 -->
      <el-form-item label="高画质流密码" prop="highQualityPassword">
        <el-input v-model="form.highQualityPassword" placeholder="请输入密码"></el-input>
        <el-button @click="addHighQualityStream" size="small" type="success">添加</el-button>
      </el-form-item>

      <!-- 高画质流地址和密码列表 -->
      <el-table :data="form.highQualityStreams" style="width: 100%">
        <el-table-column prop="url" label="地址"></el-table-column>
        <el-table-column prop="password" label="密码"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" @click="removeHighQualityStream(scope.$index)" type="danger">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 低画质流输入框 -->
      <el-form-item label="低画质流" prop="lowQualityStream">
        <el-input v-model="form.lowQualityStream" placeholder="请输入低画质流地址"></el-input>
      </el-form-item>

      <!-- 低画质流密码输入框 -->
      <el-form-item label="低画质流密码" prop="lowQualityPassword">
        <el-input v-model="form.lowQualityPassword" placeholder="请输入密码"></el-input>
        <el-button @click="addLowQualityStream" size="small" type="success">添加</el-button>
      </el-form-item>

      <!-- 低画质流地址和密码列表 -->
      <el-table :data="form.lowQualityStreams" style="width: 100%">
        <el-table-column prop="url" label="地址"></el-table-column>
        <el-table-column prop="password" label="密码"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" @click="removeLowQualityStream(scope.$index)" type="danger">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 直播分类多选框 -->
      <el-form-item label="直播分类" prop="categories">
        <el-checkbox-group v-model="form.categories">
          <el-checkbox v-for="item in categories"
                       :label="item.typeId"
                       :key="item.typeId"
          >
          {{ item.typeName }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <!-- 直播类型下拉框 -->
      <el-form-item label="直播类型" prop="liveStream">
        <el-select v-model="form.liveStream">
          <el-option
            v-for="dict in dict.type.live_stream"
            :key="dict.value"
            :label="dict.value"
            :value="dict.label"
          />
        </el-select>
        <span class="el-form-item__hint">注意：当选择'维修'时，终端上会隐藏此频道。</span>
      </el-form-item>

      <!-- 保存按钮 -->
      <el-form-item>
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { listLiveType} from "@/api/media/live/type/list";
import { listLive, getLive, delLive, addLive, updateLive } from "@/api/media/live/list";
import {getToken} from "@/utils/auth";

export default {
  dicts:['live_stream'],
  name: "LiveCreate",
  data() {
    return {
      uploadUrl: process.env.VUE_APP_BASE_API + "/common/upload",
      headers: {
        Authorization: "Bearer " + getToken()
      },
      loading: true,

      form: {
        urlId: "",
        name: "",
        image: "",
        highQualityStream: "",
        highQualityPassword: "",
        highQualityStreams: [],
        lowQualityStream: "",
        lowQualityPassword: "",
        lowQualityStreams: [],
        liveStream: "0",
        categories:[],
      },
      categories:[],
      rules: {
        urlId: [{required: true, message: '序号不能为空', trigger: 'blur'}],
        name: [{required: true, message: '直播名称不能为空', trigger: 'blur'}],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {

    getList() {
      this.loading = true;
      listLiveType().then(response => {
        this.categories = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    cancel() {
      this.open = false;
      this.$router.go(-1)
      this.reset();
    },

    reset() {
      this.form = {
        id:'',
        urlId: "",
        name: "",
        image: "",
        highQualityStream: "",
        highQualityPassword: "",
        highQualityStreams: [],
        lowQualityStream: "",
        lowQualityPassword: "",
        lowQualityStreams: [],
        categories: [],
        liveType: ""
      };
      this.resetForm("form");
    },

    // 提交表单
    submitForm() {
      this.$refs["form"].validate(valid => {
        this.$modal.loading("正在提交表单")
        if (valid) {
          let data = {
            'id':null,
            'name':this.form.name,
            'image':this.form.image,
            'highLiveStreamList':this.form.highQualityStreams,
            'lowLiveStreamList':this.form.lowQualityStreams,
            'typeId':this.form.categories,
            'urlId':this.form.urlId,
            'liveStream':this.form.liveStream
          }

          if (this.form.id != null) {
            data.id=this.form.id
            updateLive(data).then(response => {
              this.$modal.msgSuccess("直播更新成功");
              this.open = false;
              this.getList();
            }).finally(()=>{
              this.$modal.closeLoading()
              this.$router.go(-1)
            }).catch(error => {
              console.error('直播更新失败:', error);
            });
          } else {
            addLive(data).then(response => {
              this.$modal.msgSuccess("直播新增成功");
              this.open = false;
              this.getList();

            }).finally(()=>{
              this.$modal.closeLoading()
              this.$router.go(-1)
            }).catch(error => {
              console.error('直播新增失败:', error);
            });
          }
        }
      });
    },

    addHighQualityStream() {
        if(this.form.highQualityStream.startsWith('http://') || this.form.highQualityStream.startsWith('https://')){
          this.form.highQualityStreams.push({
            url: this.form.highQualityStream,
            password: this.form.highQualityPassword
          });
          this.form.highQualityStream = "";
          this.form.highQualityPassword = "";
        }else{
          alert("无效流地址")
        }

    },

    removeHighQualityStream(index) {
      this.form.highQualityStreams.splice(index, 1);
    },

    addLowQualityStream() {
      if(this.form.lowQualityStream.startsWith('http://')||this.form.lowQualityStream.startsWith('https://')){
        this.form.lowQualityStreams.push({
          url: this.form.lowQualityStream,
          password: this.form.lowQualityPassword
        });
        this.form.lowQualityStream = "";
        this.form.lowQualityPassword = "";
      }
    else{
        alert("无效流地址")
      }

    },

    removeLowQualityStream(index) {
      this.form.lowQualityStreams.splice(index, 1);
    },

    handleIconUploadSuccess(response, file, fileList) {
      this.form.image = response.url;
    },

    handleIconUploadError(err, file, fileList) {
      console.error(err);
      this.$message.error('上传失败，请稍后再试');
    },
  },

};
</script>

<style scoped>
.el-form-item__hint{
  font-size: 12px;
  color: #888;
  margin-top: 5px;
  display: block;
}
</style>
